import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, Space, message, Tabs, Image } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProForm, { ProFormCaptcha, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { Link, history, useModel, useRequest } from 'umi';
import Footer from '@/components/Footer';
import { queryDeviceAlarmNotices} from '@/services/deviceAlarm';
import WebsocketHeartbeatJs from 'websocket-heartbeat-js';
import { login } from '@/services/user';
import { rolePage } from '@/services/role';
import { queryAllDict } from '@/services/dict';
import styles from './index.less';
import bt from '@/assets/loginbt.png';
import loginbg from '@/assets/loginbg.jpg';
import loginformbg from '@/assets/loginformbg.png';


const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC = () => {
  const [submitting, setSubmitting] = useState(false);
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [roleEnum, setRoleEnum] = useState({});
  const [userName, setUserName] = useState("");
  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    const dicts = await queryAllDict();
    const alarmNotices = await queryDeviceAlarmNotices({});
    let mySocket = new WebsocketHeartbeatJs({
      url: 'ws://'+userInfo?.serviceUrl+'/ws/' + userInfo?.userId
    });
    if (userInfo) {
      await setInitialState((s) => ({ ...s, currentUser: userInfo,dicts:dicts,alarmNotices, mySocket}));
    }
  };

console.log(userName)
  const setSelectData = async () => {
    let roles=await rolePage({"roleIsdisable":0,"showSysRole":0})||[];
    let roleE={};
    for(let role of roles){
      roleE[role.roleId]=role.roleName;
    }
    setRoleEnum(roleE);
  };

  useEffect(() => {
    setSelectData();
  }, []);

  const handleSubmit = async (values: API.LoginParams) => {
    setSubmitting(true);

    try {
      // 登录
      const result = await login({ ...values });
      if (result.status === 'ok') {

        await fetchUserInfo();        
        /** 此方法会跳转到 redirect 参数所在的位置 */

        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as {
          redirect: string;
        };
        history.push(redirect || '/');
        return;
      } // 如果失败去设置用户错误信息

      setUserLoginState(result);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }

    setSubmitting(false);
  };

  const { status, errorMsg } = userLoginState;
  return (
    <div className={styles.logincontainer} style={{ backgroundImage: 'url(' + loginbg + ') no-repeat center center' }}>
      <div className={styles.content}>
        <div className={styles.top}>
          <Image className={styles.topImg} src={bt} preview={false} />
        </div>
        <div className={styles.main} style={{ backgroundImage: 'url(' + loginformbg + ') no-repeat center top' }}>
          <ProForm
            initialValues={{
              autoLogin: true,
              // role:'0'
            }}
            submitter={{
              searchConfig: {
                submitText: '登录',
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading: submitting,
                size: 'large',
                style: {
                  height: '45px',
                  background: '-webkit-gradient(linear, 0 0, 0 100%, from(#07a7ff), to(#355fb8))',
                  width: '100%',
                  border: 0
                },
              },
            }}
            onFinish={async (values) => {
              await handleSubmit(values as API.LoginParams);
            }}
          >
            {status === 'error' && (
              <LoginMessage content={errorMsg??'用户名和密码错误'} />
            )}
            <>
              <div className={styles.divselect}>
                <UserOutlined className={styles.icon} />
                <ProFormSelect
                  className={styles.input}
                  name="role"
                  valueEnum={roleEnum}
                  fieldProps={{
                    size: 'large',
                    dropdownStyle: { backgroundColor: '#355fb8' },
                  }}
                  placeholder="请选择用户类型"
                  rules={[userName!="admin"?{ required: true, message: '请选择用户类型!' }:{}]}
                /> 
              </div>
              <ProFormText
                 className={styles.input}
                name="userName"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                onChange={(e)=>setUserName(e.target.value)}
                placeholder="请输入用户名"
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                className={styles.input}
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,

                }}
                placeholder="请输入密码"
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
            </>
          </ProForm>
        </div>
        <div className={styles.companyname}>
          <a >陕西光环网络科技有限公司</a>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
